package com.example.demo.controller;

import com.example.demo.entity.TeacherCourse;
import com.example.demo.service.TeacherCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/teacher_courses")
public class TeacherCourseController {

    @Autowired
    private TeacherCourseService service;

    // POST /api/teacher_courses/{teacherId}/courses/{courseId}
    @PostMapping("/{teacherId}/courses/{courseId}")
    public ResponseEntity<?> createAssociation(
            @PathVariable("teacherId") String teacherId,
            @PathVariable("courseId") String courseId) {

        try {
            // 1. 调用 Service 方法，获取 Optional 结果
            Optional<TeacherCourse> associationOpt = service.createAssociation(teacherId, courseId);

            if (associationOpt.isPresent()) {
                // 2. 成功创建 (Optional 包含 TeacherCourse 对象)
                // 返回 ResponseEntity<TeacherCourse>
                return new ResponseEntity<>(associationOpt.get(), HttpStatus.CREATED);
            } else {
                // 3. 关联已存在 (Optional 为 Empty)
                // 返回 ResponseEntity<String>
                return ResponseEntity.status(HttpStatus.CONFLICT).body("该教师与课程的关联已存在。");
            }

        } catch (RuntimeException e) {
            // 4. Service 层抛出异常 (如外键不存在)
            // 返回 ResponseEntity<String>
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    // DELETE /api/teacher_courses/{teacherId}/courses/{courseId}
    // 解除关联
    @DeleteMapping("/{teacherId}/courses/{courseId}")
    public ResponseEntity<?> deleteAssociation(
            @PathVariable("teacherId") String teacherId,
            @PathVariable("courseId") String courseId) {

        if (service.deleteAssociation(teacherId, courseId)) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("关联记录不存在或已删除。"); // 404 Not Found
        }
    }

    // GET /api/teacher_courses/teacher/{teacherId}
    // 查询某个教师关联的所有课程ID记录
    @GetMapping("/teacher/{teacherId}")
    public List<TeacherCourse> getCoursesByTeacher(@PathVariable("teacherId") String teacherId) {
        // 实际业务中，您可能需要 JOIN 查询 Course 表并返回 Course 实体列表

        return service.findAssociationsByTeacherId(teacherId);
    }

    // GET /api/teacher_courses/course/{courseId}
    // 查询某个课程关联的所有教师ID记录
    @GetMapping("/course/{courseId}")
    public List<TeacherCourse> getTeachersByCourse(@PathVariable("courseId") String courseId) {
        // 实际业务中，您可能需要 JOIN 查询 Teacher 表并返回 Teacher 实体列表
        return service.findAssociationsByCourseId(courseId);
    }
}